/* components */
import { BaseSelectUserSelectedPanelItem } from '@src/component/common/BaseSelectUser/components'
/* enum */
import { BaseSelectUserComponentNameEnum, BaseSelectUserSelectedItem } from '@src/component/common/BaseSelectUser/model'
/* hooks */
import { useSelectUserCheckedItemList } from '@src/component/common/BaseSelectUser/hooks'
/* scss */
import '@src/component/common/BaseSelectUser/components/SelectedPanel/index.scss'
/* vue */
// @ts-ignore
import { ComponentInstance, ComponentRenderProxy, computed, ComputedRef, defineComponent, PropType } from 'vue'
import { CommonComponentInstance } from '@model/VC'
import { CreateElement } from 'vue'
/* util */
import { t } from '@src/locales'
import { 
  isDepartmentSelectType, 
  isDynamicSelectType, 
  isRoleSelectType, 
  isServiceProviderSelectType, 
  isTagSelectType, 
  isUserSelectType
} from '@src/component/common/BaseSelectUser/util'
import { uuid } from '@src/util/lang/string'
import { findComponentsDownward, findComponentUpward } from '@src/util/assist'
/* types */
import { BaseSelectUserSelectedItemType } from '@src/component/common/BaseSelectUser/types'

const BaseSelectUserSelectedCountDataKeyCNNameEnum: Record<string, string> = {
  user: t('common.label.member'),
  department: t('common.label.department'),
  role: t('common.label.role'),
  serviceProvider: t('common.label.serviceProvider'),
}

type BaseSelectUserSelectedCountDataType = {
  [x: string]: number;
  user: number;
  department: number;
  role: number;
  serviceProvider: number;
}

export type SelectedPanelProps = {
  
}

export interface SelectedPanelSetupState {
  
}

export enum SelectedPanelEmitEventNameEnum {
  Input = 'input',
}

export type SelectedPanelInstance = ComponentInstance & SelectedPanelSetupState
export type SelectedPanelVM = ComponentRenderProxy<SelectedPanelProps> & CommonComponentInstance & SelectedPanelInstance

export default defineComponent({
  name: BaseSelectUserComponentNameEnum.BaseSelectUserSelectedPanel,
  emits: [
    SelectedPanelEmitEventNameEnum.Input
  ],
  props: {
    
  },
  setup(props: SelectedPanelProps, { emit }) {
    
    const { checkedItemList, checkedItemListForComponent, removeCheckedItem, removeAllCheckedItem } = useSelectUserCheckedItemList()
    
    const selectedCountData: ComputedRef<BaseSelectUserSelectedCountDataType> = computed(() => {
      
      let countData: BaseSelectUserSelectedCountDataType = {
        user: 0,
        department: 0,
        role: 0,
        serviceProvider: 0,
      }
      
      checkedItemList.value.forEach(item => {
        
        if (isDepartmentSelectType(item) || isTagSelectType(item)) {
          countData.department++
        }
        
        if (isRoleSelectType(item)) {
          countData.role++
        }
        
        if (isServiceProviderSelectType(item)) {
          countData.serviceProvider++
        }
        
        if (isUserSelectType(item)) {
          countData.user++
        }
        
        if (isDynamicSelectType(item)) {
          countData.user++
        }
        
      })
      
      return countData
      
    })
    
    const selectedCountDataDisplayText: ComputedRef<string> = computed(() => {
      return (
        Object.keys(selectedCountData.value)
        .filter((key) => {
          return selectedCountData.value[key] > 0
        })
        .map(key => {
          return t('component.baseSelectUser.selectedCount', { count: selectedCountData.value[key], somthing: BaseSelectUserSelectedCountDataKeyCNNameEnum[key] }); //`${selectedCountData.value[key]}个${BaseSelectUserSelectedCountDataKeyCNNameEnum[key]}`
        })
        .join('、')
      )
    })
    
    const isCheckedItemListNotEmpty = computed(() => {
      return checkedItemList.value.length > 0
    })
    
    const onSelectedItemRemoveHandler = (item: BaseSelectUserSelectedItemType) => {
      removeCheckedItem(item)
    }
    
    return {
      checkedItemList,
      selectedCountData,
      selectedCountDataDisplayText,
      isCheckedItemListNotEmpty,
      checkedItemListForComponent,
      
      removeAllCheckedItem,
      onSelectedItemRemoveHandler
    }
    
  },
  watch: {
    checkedItemList: {
      handler(newVal, oldVal) {
        if(newVal && oldVal && newVal.length > oldVal.length) {
          // 选中列表的元素
          const itemsElement = this.$refs.BaseSelectUserSelectedPanelItemsElement as HTMLElement
          // 滚动到最下面
          if (itemsElement) {
            this.$nextTick(() => {
              itemsElement.scrollTop = itemsElement.clientHeight
            })
          }
        }
      }
    }
  },
  methods: {
    getTreeComponents() {
      const baseSelectUserComponent = findComponentUpward(this, BaseSelectUserComponentNameEnum.BaseSelectUser) || {}
      const treeComponents = findComponentsDownward(baseSelectUserComponent, 'ElTree') || []
      
      return treeComponents
    },
    onResetButtonClickHandler() {
      this.removeAllCheckedItem()
      this.resetTreeNodeSelected()
    },
    resetTreeNodeSelected() {
      
      const treeComponents = this.getTreeComponents()
      
      treeComponents.forEach((treeComponent: any) => {
        treeComponent.setCheckedKeys([])
      })
    }
  },
  render(h: CreateElement) {
    return (
      <div class={BaseSelectUserComponentNameEnum.BaseSelectUserSelectedPanel}>
        
        <div class="base-select-user-selected-panel__title">
          
          <span class="base-select-user-selected-panel__title-text">
            {t('common.base.selected2')}
          </span>
          
          {this.isCheckedItemListNotEmpty && (
            <span 
              class="base-select-user-selected-panel__reset"
              onClick={this.onResetButtonClickHandler}
            >
              {t('common.base.clear')}
            </span>
          )}
          
        </div>
        
        {this.isCheckedItemListNotEmpty && (
          <div class="base-select-user-selected-panel__info">
            <div class="base-select-user-selected-panel__count">
              { this.selectedCountDataDisplayText }
            </div>
          </div>
        )}
        
        <div class="base-select-user-selected-panel__items" ref="BaseSelectUserSelectedPanelItemsElement">
          {this.checkedItemListForComponent.map(item => {
            return (
              <BaseSelectUserSelectedPanelItem 
                key={uuid()} 
                value={item} 
                onRemove={this.onSelectedItemRemoveHandler} 
              />
            )
          })}
        </div>
        
      </div>
    )
  }
})
